<?php
/**
 * FastApp.
 * 11/4/24
 * @Author deepsea
 * @Contact (telegram:deepsea159)
 */

namespace App\Spider;

use CpChart\Chart\Bubble;
use CpChart\Chart\Radar;
use CpChart\Chart\Scatter;
use CpChart\Chart\Split;
use CpChart\Chart\Spring;
use CpChart\Chart\Stock;
use CpChart\Chart\Surface;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\WebDriverWait;
use Hyperf\DbConnection\Db;
use CpChart\Chart\Pie;
use CpChart\Data;
use CpChart\Image;

class ReportForms
{
    public static function finance(array $indicators): void
    {
        //cyclicity 0年1月2周3天4Q(季度)
        $serverUrl = 'http://localhost:4444';
        $driver = RemoteWebDriver::create($serverUrl, DesiredCapabilities::chrome());
        foreach ($indicators as $item) {
            $driver->get($item['url']);
            $wait = new WebDriverWait($driver, 10);
            $wait->until(WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::id('trading_chart')));
            console()->info('us-' . $item['type']);
            //1=>1Y;2=>3Y;3=>5Y
            if (!empty($item['btn'])) {
                sleep(1);
                $driver->findElement(WebDriverBy::cssSelector($item['btn']))->click();
                sleep(2);
            }
            sleep(1);
            $scriptX = "return Highcharts.charts[0].series[0].data.map(function(point) { return point.x; })";
            $resultX = $driver->executeScript($scriptX);
            $scriptY = "return Highcharts.charts[0].series[0].data.map(function(point) { return point.y; })";
            $resultY = $driver->executeScript($scriptY);
            $description = '';
            try {
                $description = $driver->findElement(WebDriverBy::id('description'))->getText();
            } catch (\Throwable) {
            }
            $map = ['currency' => $item['currency'], 'type' => $item['type'], 'date' => date('Y-m-d')];
            Db::table('report_form')->where($map)->delete();
            $map['content'] = json_encode(['x' => $resultX, 'y' => $resultY]);
            $map['description'] = $description;
            $map['unit'] = $item['unit'];
            $map['cyclicity'] = $item['cyclicity'] ?? 1;
            $map['duration'] = $item['duration'] ?? 5;
            Db::table('report_form')->insert($map);
        }
        $driver->quit();
    }

    public static array $title = [
        1 => [
            1 => '失业率',
            2 => '通胀率',
            3 => 'M0',
            4 => 'M1,M2',
            6 => '银行资产负债表',
            7 => '美联储资产负债表',
            8 => '外国债券投资',
            9 => '联邦基金利率',
            10 => '2,10年期国债收益率与有效联邦基金利率',
            11 => '10年期国债收益率',
            12 => '原油产量',
            13 => '比特币汇率',
            14 => '军费',
            15 => '政府债务',
            16 => '有效联邦基金利率',
            17 => '整体净资本流动',
            18 => '进出口',
            19 => '进口',
            20 => '贸易差额',
            21 => 'CPI',
            22 => '商业PMI',
            23 => '消费者PMI',
        ],
        2 => [
            1 => '失业率',
            2 => '通胀率',
            3 => 'm0',
            4 => 'm1',
            5 => 'm2',
            6 => '央行资产负债表',
            7 => '外国债券投资',
            8 => '利率',
            9 => '2年期国债收益率',
            10 => '10年期国债收益率',
            11 => '军费(USD)',
            12 => '整体净资本流动',
            13 => '出口',
            14 => '进口',
            15 => '贸易差额',
            16 => 'CPI',
            17 => '商业PMI',
            18 => '消费者PMI',
            19 => '30年期国债收益率',
            20 => '人口',
            21 => '全年GDP增长',
            22 => '新屋开工（年）',
            23 => '房屋开工率',
            24 => '政府支出',
            25 => '政府债务占国内生产总值比重',
            26 => '工资',
            27 => '私人债务占国内生产总值',
            28 => '政府采购 - 财政部 - 债券',
        ],
        3 => [
            1 => '失业率',
            2 => '通胀率',
            3 => 'm0',
            4 => 'm1',
            5 => 'm2',
            6 => '银行资产负债表',
            7 => '央行资产负债表',
            8 => '一年期贷款利率',
            9 => '2年期国债收益率',
            10 => '10年期国债收益率',
            11 => '军费(USD)',
            12 => '整体净资本流动(USD)',
            13 => '出口(USD)',
            14 => '进口(USD)',
            15 => '贸易差额(USD)',
            16 => 'CPI',
            17 => '商业PMI',
            18 => '消费者PMI',
            19 => '30年期国债收益率',
            20 => '人口',
            21 => '全年GDP增长',
            22 => '住宅物业价格',
            23 => '房屋开工',
            24 => '政府支出',
            25 => '政府债务占国内生产总值比重',
            26 => '工资',
            27 => '零售销售（年率同比)',
            28 => '固定资产投资',
            29 => '存款准备金率',
            30 => '反向回购利率',
            31 => '14天逆回购利率',
            32 => '外汇储备(USD)',
            33 => '通过反向回购注入流动性',
            34 => '五期贷款利率',
            35 => '银行贷款',
            36 => '1 年期 MLF 利率',
            37 => '总计社会融资/私营部门贷款',
            38 => '贷款增长/未偿贷款增长 (同比)',
        ]
    ];

    public static function us(): void
    {
        self::finance([
            //失业率
            ['type' => 1, 'url' => 'https://zh.tradingeconomics.com/united-states/unemployment-rate', 'currency' => 1, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //通胀率
            ['type' => 2, 'url' => 'https://zh.tradingeconomics.com/united-states/inflation-cpi', 'currency' => 1, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //m0
            ['type' => 3, 'url' => 'https://zh.tradingeconomics.com/united-states/money-supply-m0', 'currency' => 1, 'unit' => 'M', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //m1
            ['type' => 4, 'url' => 'https://zh.tradingeconomics.com/united-states/money-supply-m1', 'currency' => 1, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //m2
            ['type' => 5, 'url' => 'https://zh.tradingeconomics.com/united-states/money-supply-m2', 'currency' => 1, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //银行资产负债表
            ['type' => 6, 'url' => 'https://zh.tradingeconomics.com/united-states/banks-balance-sheet', 'currency' => 1, 'unit' => 'B', 'cyclicity' => 2, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //美联储资产负债表
            ['type' => 7, 'url' => 'https://zh.tradingeconomics.com/united-states/central-bank-balance-sheet', 'currency' => 1, 'unit' => 'M', 'cyclicity' => 2, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //外国债券投资
            ['type' => 8, 'url' => 'https://zh.tradingeconomics.com/united-states/foreign-bond-investment', 'currency' => 1, 'unit' => 'M', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //联邦基金利率
            ['type' => 9, 'url' => 'https://zh.tradingeconomics.com/united-states/interest-rate', 'currency' => 1, 'unit' => '%', 'cyclicity' => 99, 'btn' => '#dateSpansDiv > a:nth-child(2)'],
            //2年期国债收益率
            ['type' => 10, 'url' => 'https://zh.tradingeconomics.com/united-states/2-year-note-yield', 'currency' => 1, 'unit' => '%', 'cyclicity' => 3, 'duration' => 1],
            //10年期国债收益率
            ['type' => 11, 'url' => 'https://zh.tradingeconomics.com/united-states/government-bond-yield', 'currency' => 1, 'unit' => '%', 'cyclicity' => 3, 'duration' => 1],
            //原油产量
            ['type' => 12, 'url' => 'https://zh.tradingeconomics.com/united-states/crude-oil-production', 'currency' => 1, 'unit' => 'K', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //比特币汇率
            ['type' => 13, 'url' => 'https://zh.tradingeconomics.com/btcusd:cur', 'currency' => 1, 'cyclicity' => 2, 'duration' => 1, 'unit' => '', 'btn' => '#trading_chart > div > div.iChart-wrapper-footer > div.iChart-menu2-bottom-cnt-horizontal > a:nth-child(6)'],
            //军费
            ['type' => 14, 'url' => 'https://zh.tradingeconomics.com/united-states/military-expenditure', 'currency' => 1, 'unit' => 'M', 'cyclicity' => 0],
            //政府债务
            ['type' => 15, 'url' => 'https://zh.tradingeconomics.com/united-states/government-debt', 'currency' => 1, 'unit' => 'M', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //有效联邦基金利率
            ['type' => 16, 'url' => 'https://zh.tradingeconomics.com/united-states/effective-federal-funds-rate', 'currency' => 1, 'unit' => '%', 'cyclicity' => 3, 'duration' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //整体净资本流动
            ['type' => 17, 'url' => 'https://zh.tradingeconomics.com/united-states/capital-flows', 'currency' => 1, 'unit' => 'M', 'cyclicity' => 1],
            //出口
            ['type' => 18, 'url' => 'https://zh.tradingeconomics.com/united-states/exports', 'currency' => 1, 'unit' => 'B', 'cyclicity' => 1],
            //进口
            ['type' => 19, 'url' => 'https://zh.tradingeconomics.com/united-states/imports', 'currency' => 1, 'unit' => 'B', 'cyclicity' => 1],
            //贸易差额
            ['type' => 20, 'url' => 'https://zh.tradingeconomics.com/united-states/balance-of-trade', 'currency' => 1, 'unit' => 'B', 'cyclicity' => 1],
            //CPI
            ['type' => 21, 'url' => 'https://zh.tradingeconomics.com/united-states/consumer-price-index-cpi', 'currency' => 1, 'unit' => 'Point', 'cyclicity' => 1],
            //商业PMI
            ['type' => 22, 'url' => 'https://zh.tradingeconomics.com/united-states/business-confidence', 'currency' => 1, 'unit' => 'Point', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //消费者PMI
            ['type' => 23, 'url' => 'https://zh.tradingeconomics.com/united-states/consumer-confidence', 'currency' => 1, 'unit' => 'Point', 'cyclicity' => 1],
        ]);
    }

    public static function usImage(): void
    {
        $res = Db::table('report_form')->where(['currency' => 1])->get()->mapWithKeys(function ($item) {
            return [$item->type => (array)$item];
        });
        $indicators = [
            1, 2, 3, 6, 7, 8, 9, 12, 13, 14, 15, 22,
            [4, 5],
            [10, 11, 16],
            [20, 18, 19, 17],
            [21, 23],
        ];
        $def_setting = [
            'canvasWidth' => 830,
            'canvasHeight' => 420,
            'graphAreaWidth' => 700,
            'graphAreaHeight' => 230,
        ];
        $image_setting = [
            2 => array_merge($def_setting, ['canvasHeight' => 500]),
            3 => array_merge($def_setting, ['canvasHeight' => 380, 'title_tag' => '(万亿美元)', 'title_tag_x' => 395]),
            4 => array_merge($def_setting, ['canvasHeight' => 380, 'title_tag' => '(万亿美元)', 'title_tag_x' => 410, 'line_tag' => ['M1', 'M2'], 'line_tag_x' => 800]),
            6 => array_merge($def_setting, ['canvasHeight' => 360, 'title_tag' => '(万亿美元)', 'title_tag_x' => 460, 'title_tag_y' => 25, 'LabelSkip' => 1,]),
            7 => array_merge($def_setting, ['canvasHeight' => 360, 'title_tag' => '(万亿美元)', 'title_tag_x' => 470, 'title_tag_y' => 25, 'InnerTickWidth' => 2, 'OuterTickWidth' => 0]),
            8 => array_merge($def_setting, ['canvasHeight' => 360, 'title_tag' => '(亿美元)', 'title_tag_x' => 440, 'title_tag_y' => 25, 'unit_rate' => 1000]),
            9 => array_merge($def_setting, ['canvasHeight' => 450, 'title_tag_y' => 25]),
            10 => array_merge($def_setting, ['canvasHeight' => 450, 'line_tag' => ['2年', '10年', '利率'], 'line_tag_x' => 800]),
            12 => array_merge($def_setting, ['canvasHeight' => 380, 'title_tag' => '(桶/日/千升)', 'title_tag_x' => 430, 'title_tag_y' => 25, 'yFormat' => ['rate' => 1000, 'unit' => 'k']]),
            13 => array_merge($def_setting, ['canvasHeight' => 330, 'title_tag' => '(美元)', 'title_tag_x' => 430, 'title_tag_y' => 25, 'LabelSkip' => 1]),
            14 => array_merge($def_setting, ['canvasHeight' => 380, 'title_tag' => '(亿美元)', 'title_tag_x' => 400, 'title_tag_y' => 25, 'unit_rate' => 100]),
            15 => array_merge($def_setting, ['canvasHeight' => 380, 'title_tag' => '(万亿美元)', 'title_tag_x' => 430, 'title_tag_y' => 25,]),
            17 => ['unit_rate' => 1000],
            20 => array_merge($def_setting, ['canvasHeight' => 460, 'canvasWidth' => 865, 'title_tag' => '(亿美元)', 'title_tag_x' => 410, 'title_tag_y' => 25, 'unit_rate' => 1, 'line_tag' => ['差额', '出口', '进口', '净资本流动'], 'line_tag_x' => 800]),
            21 => array_merge($def_setting, ['canvasHeight' => 410, 'canvasWidth' => 865, 'title_tag' => '(亿美元)', 'title_tag_x' => 410, 'title_tag_y' => 25, 'unit_rate' => 1, 'line_tag' => ['CPI', '消费者PMI'], 'line_tag_x' => 800]),
            22 => array_merge($def_setting, ['canvasHeight' => 450, 'title_tag_y' => 25]),
        ];
        foreach ($indicators as $indicator) {
            $indicator = is_array($indicator) ? $indicator : [$indicator];
            $min = $max = $line = $xAxis = $yAxis = [];
            $description = $title = $ypop = 0;
            $setting = $image_setting[$indicator[0]] ?? $def_setting;
            foreach ($indicator as $v) {
                $setting = array_merge($setting, $image_setting[$v] ?? []);
                $cnt = json_decode($res[$v]['content'], true);
                $cnt['x'] = array_filter($cnt['x']);
                $cnt['y'] = array_filter($cnt['y']);
                $cyclicity = $setting['cyclicity'] ?? $res[$v]['cyclicity'];
                if ($cyclicity == 1) {
                    $x = array_map(function ($t) {
                        $year = date('Y', $t / 1000);
                        $month = date('m', $t / 1000);
                        if ($year == date('Y')) {
                            if ($month == 1) {
                                return $year;
                            } elseif ($month == 7) {
                                return $month;
                            }
                        } elseif ($month == 1) {
                            return $year;
                        } elseif ($month == 7) {
                            return $month;
                        }
                        return '';
                    }, $cnt['x']);
                } elseif ($cyclicity == 2) {
                    $x = [];
                    $ya = 0;
                    foreach ($cnt['x'] as $t) {
                        $year = date('Y', $t / 1000);
                        if (!$ya) $ya = $year;
                        if (in_array($year, $x) || $ya == $year) $x[] = '';
                        else $x[] = $year;
                    }
                } elseif ($cyclicity == 3) {
                    $x = [];
                    $ym = [];
                    $cd = date('Y');
                    foreach ($cnt['x'] as $t) {
                        $year = date('Y', $t / 1000);
                        $m = date('m', $t / 1000);
                        if ($cd == $year && $m > date('m')) {
                            $ypop++;
                            continue;
                        }
                        if (in_array($m, $ym[$year] ?? [])) $ym[$year][] = ''; else  $ym[$year][] = $m;
                    }
                    foreach ($ym as $y) {
                        $x = array_merge($x, $y);
                    }
                } elseif (!$cyclicity) {//年
                    $x = [];
                    foreach ($cnt['x'] as $t) $x[] = date('Y', $t / 1000);
                } else {
                    $x = [];
                    $cd = date('Y');
                    foreach ($cnt['x'] as $t) {
                        $year = date('Y', $t / 1000);
                        if (($cd - $year) > ($res[$v]['duration'] - 1)) $x[] = '';
                        else $x[] = in_array($year, $x) ? '' : $year;
                    }
                }
                if ($res[$v]['unit'] == 'M') $l = array_map(function ($v) use ($setting) {
                    return bcdiv($v . '', '' . ($setting['unit_rate'] ?? 1000000), 2);
                }, $cnt['y']);
                elseif ($res[$v]['unit'] == 'B') $l = array_map(function ($v) use ($setting) {
                    return bcdiv($v . '', '' . ($setting['unit_rate'] ?? 1000), 2);
                }, $cnt['y']);
                else $l = $cnt['y'];
                if (isset($setting['yFormat'])) {
                    $l = array_map(function ($v) use ($setting) {
                        return bcdiv($v . '', '' . $setting['yFormat']['rate'], 1);
                    }, $l);
                }
                if ($ypop) $l = array_splice($l, -$ypop);
                $xAxis = count($xAxis) < count($x) ? $x : $xAxis;
                $yAxis = count($yAxis) < count($l) ? $l : $yAxis;
                $line[] = $l;
                $description = $description ?: $res[$v]['description'];
                $title = $title ?: self::$title[1][$res[$v]['type']];
                $max[] = max($l);
                $min[] = min($l);
            }
//            print_r($line);
//            print_r($max);
//            print_r($min);
//            exit();
            $path = self::image([
                'line' => $line,
                'x' => $xAxis,
                'y' => $yAxis,
                'max' => max($max),
                'min' => min($min),
                'description' => $description,
                'title' => $title,
                'setting' => $setting,
            ], 1);
            print_r($path . PHP_EOL);
        }
    }

    public static function jp(): void
    {
        self::finance([
            //失业率
            ['type' => 1, 'url' => 'https://zh.tradingeconomics.com/japan/unemployment-rate', 'currency' => 2, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //通胀率
            ['type' => 2, 'url' => 'https://zh.tradingeconomics.com/japan/inflation-cpi', 'currency' => 2, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //m0
            ['type' => 3, 'url' => 'https://zh.tradingeconomics.com/japan/money-supply-m0', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //m1
            ['type' => 4, 'url' => 'https://zh.tradingeconomics.com/japan/money-supply-m1', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //m2
            ['type' => 5, 'url' => 'https://zh.tradingeconomics.com/japan/money-supply-m2', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //央行资产负债表
            ['type' => 6, 'url' => 'https://zh.tradingeconomics.com/japan/central-bank-balance-sheet', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //外国债券投资
            ['type' => 7, 'url' => 'https://zh.tradingeconomics.com/japan/foreign-bond-investment', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 2, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //利率
            ['type' => 8, 'url' => 'https://zh.tradingeconomics.com/japan/interest-rate', 'currency' => 2, 'unit' => '%', 'cyclicity' => 1],
            //2年期国债收益率
            ['type' => 9, 'url' => 'https://zh.tradingeconomics.com/japan/2-year-note-yield', 'currency' => 2, 'unit' => '%', 'cyclicity' => 3, 'duration' => 1],
            //10年期国债收益率
            ['type' => 10, 'url' => 'https://zh.tradingeconomics.com/japan/government-bond-yield', 'currency' => 2, 'unit' => '%', 'cyclicity' => 3, 'duration' => 1],
            //军费(USD)
            ['type' => 11, 'url' => 'https://zh.tradingeconomics.com/japan/military-expenditure', 'currency' => 2, 'unit' => 'M', 'cyclicity' => 0],
            //整体净资本流动
            ['type' => 12, 'url' => 'https://zh.tradingeconomics.com/japan/capital-flows', 'currency' => 2, 'unit' => 'M', 'cyclicity' => 1],
            //出口
            ['type' => 13, 'url' => 'https://zh.tradingeconomics.com/japan/exports', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 1],
            //进口
            ['type' => 14, 'url' => 'https://zh.tradingeconomics.com/japan/imports', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 1],
            //贸易差额
            ['type' => 15, 'url' => 'https://zh.tradingeconomics.com/japan/balance-of-trade', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 1],
            //CPI
            ['type' => 16, 'url' => 'https://zh.tradingeconomics.com/japan/consumer-price-index-cpi', 'currency' => 2, 'unit' => 'Point', 'cyclicity' => 1],
            //商业PMI
            ['type' => 17, 'url' => 'https://zh.tradingeconomics.com/japan/business-confidence', 'currency' => 2, 'unit' => 'Point', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //消费者PMI
            ['type' => 18, 'url' => 'https://zh.tradingeconomics.com/japan/consumer-confidence', 'currency' => 2, 'unit' => 'Point', 'cyclicity' => 1],
            //30年期国债收益率
            ['type' => 19, 'url' => 'https://zh.tradingeconomics.com/japan/30-year-bond-yield', 'currency' => 2, 'unit' => '%', 'cyclicity' => 3, 'duration' => 1],
            //人口
            ['type' => 20, 'url' => 'https://zh.tradingeconomics.com/japan/population', 'currency' => 2, 'unit' => 'M', 'cyclicity' => 0],
            //全年GDP增长
            ['type' => 21, 'url' => 'https://zh.tradingeconomics.com/japan/full-year-gdp-growth', 'currency' => 2, 'unit' => '%', 'cyclicity' => 0],
            //新屋开工（年）
            ['type' => 22, 'url' => 'https://zh.tradingeconomics.com/japan/housing-starts-yoy', 'currency' => 2, 'unit' => '%', 'cyclicity' => 1],
            //房屋开工率
            ['type' => 23, 'url' => 'https://zh.tradingeconomics.com/japan/housing-starts', 'currency' => 2, 'unit' => '套', 'cyclicity' => 1],
            //政府支出
            ['type' => 24, 'url' => 'https://zh.tradingeconomics.com/japan/government-spending', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 4, 'btn' => '#dateSpansDiv > a:nth-child(2)'],
            //政府债务占国内生产总值比重
            ['type' => 25, 'url' => 'https://zh.tradingeconomics.com/japan/government-debt-to-gdp', 'currency' => 2, 'unit' => 'Point', 'cyclicity' => 0],
            //工资
            ['type' => 26, 'url' => 'https://zh.tradingeconomics.com/japan/wages', 'currency' => 2, 'unit' => '日元', 'cyclicity' => 1],
            //私人债务占国内生产总值
            ['type' => 27, 'url' => 'https://zh.tradingeconomics.com/japan/private-debt-to-gdp', 'currency' => 2, 'unit' => '%', 'cyclicity' => 0],
            //政府采购 - 财政部 - 债券
            ['type' => 28, 'url' => 'https://zh.tradingeconomics.com/japan/purchases-of-government-bonds', 'currency' => 2, 'unit' => 'B', 'cyclicity' => 1],
        ]);
    }

    public static function zh(): void
    {
        self::finance([
            //失业率
            ['type' => 1, 'url' => 'https://zh.tradingeconomics.com/china/unemployment-rate', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //通胀率
            ['type' => 2, 'url' => 'https://zh.tradingeconomics.com/china/inflation-cpi', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //m0
            ['type' => 3, 'url' => 'https://zh.tradingeconomics.com/china/money-supply-m0', 'currency' => 3, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //m1
            ['type' => 4, 'url' => 'https://zh.tradingeconomics.com/china/money-supply-m1', 'currency' => 3, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //m2
            ['type' => 5, 'url' => 'https://zh.tradingeconomics.com/china/money-supply-m2', 'currency' => 3, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //银行资产负债表
            ['type' => 6, 'url' => 'https://zh.tradingeconomics.com/china/banks-balance-sheet', 'currency' => 3, 'unit' => 'B', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //央行资产负债表
            ['type' => 7, 'url' => 'https://zh.tradingeconomics.com/china/central-bank-balance-sheet', 'currency' => 3, 'unit' => 'M', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //一年期贷款利率
            ['type' => 8, 'url' => 'https://zh.tradingeconomics.com/china/interest-rate', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1],
            //2年期国债收益率
            ['type' => 9, 'url' => 'https://zh.tradingeconomics.com/china/2-year-note-yield', 'currency' => 3, 'unit' => '%', 'cyclicity' => 3, 'duration' => 1],
            //10年期国债收益率
            ['type' => 10, 'url' => 'https://zh.tradingeconomics.com/china/government-bond-yield', 'currency' => 3, 'unit' => '%', 'cyclicity' => 3, 'duration' => 1],
            //军费(USD)
            ['type' => 11, 'url' => 'https://zh.tradingeconomics.com/china/military-expenditure', 'currency' => 3, 'unit' => 'M', 'cyclicity' => 0],
            //整体净资本流动(USD)
            ['type' => 12, 'url' => 'https://zh.tradingeconomics.com/china/capital-flows', 'currency' => 3, 'unit' => 'M', 'cyclicity' => 4],
            //出口(USD)
            ['type' => 13, 'url' => 'https://zh.tradingeconomics.com/china/exports', 'currency' => 3, 'unit' => 'B', 'cyclicity' => 1],
            //进口(USD)
            ['type' => 14, 'url' => 'https://zh.tradingeconomics.com/china/imports', 'currency' => 3, 'unit' => 'B', 'cyclicity' => 1],
            //贸易差额(USD)
            ['type' => 15, 'url' => 'https://zh.tradingeconomics.com/china/balance-of-trade', 'currency' => 3, 'unit' => 'B', 'cyclicity' => 1],
            //CPI
            ['type' => 16, 'url' => 'https://zh.tradingeconomics.com/china/consumer-price-index-cpi', 'currency' => 3, 'unit' => 'Point', 'cyclicity' => 1],
            //商业PMI
            ['type' => 17, 'url' => 'https://zh.tradingeconomics.com/china/business-confidence', 'currency' => 3, 'unit' => 'Point', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //消费者PMI
            ['type' => 18, 'url' => 'https://zh.tradingeconomics.com/china/consumer-confidence', 'currency' => 3, 'unit' => 'Point', 'cyclicity' => 1],
            //30年期国债收益率
            ['type' => 19, 'url' => 'https://zh.tradingeconomics.com/china/30-year-bond-yield', 'currency' => 3, 'unit' => '%', 'cyclicity' => 3, 'duration' => 1],
            //人口
            ['type' => 20, 'url' => 'https://zh.tradingeconomics.com/china/population', 'currency' => 3, 'unit' => 'M', 'cyclicity' => 0],
            //全年GDP增长
            ['type' => 21, 'url' => 'https://zh.tradingeconomics.com/china/full-year-gdp-growth', 'currency' => 3, 'unit' => '%', 'cyclicity' => 0],
            //住宅物业价格
            ['type' => 22, 'url' => 'https://zh.tradingeconomics.com/china/residential-property-prices', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1],
            //房屋开工
            ['type' => 23, 'url' => 'https://zh.tradingeconomics.com/china/housing-starts', 'currency' => 3, 'unit' => '套', 'cyclicity' => 1],
            //政府支出
            ['type' => 24, 'url' => 'https://zh.tradingeconomics.com/china/government-spending', 'currency' => 3, 'unit' => 'B', 'cyclicity' => 0],
            //政府债务占国内生产总值比重
            ['type' => 25, 'url' => 'https://zh.tradingeconomics.com/china/government-debt-to-gdp', 'currency' => 3, 'unit' => 'Point', 'cyclicity' => 0],
            //工资
            ['type' => 26, 'url' => 'https://zh.tradingeconomics.com/china/wages', 'currency' => 3, 'unit' => 'CNY', 'cyclicity' => 0],
            //零售销售（年率同比)
            ['type' => 27, 'url' => 'https://zh.tradingeconomics.com/china/retail-sales-annual', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //固定资产投资
            ['type' => 28, 'url' => 'https://zh.tradingeconomics.com/china/fixed-asset-investment', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //存款准备金率
            ['type' => 29, 'url' => 'https://zh.tradingeconomics.com/china/cash-reserve-ratio', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //反向回购利率
            ['type' => 30, 'url' => 'https://zh.tradingeconomics.com/china/reverse-repo-rate', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //14天逆回购利率
            ['type' => 31, 'url' => 'https://zh.tradingeconomics.com/china/14-day-reverse-repo-rate', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //外汇储备(USD)
            ['type' => 32, 'url' => 'https://zh.tradingeconomics.com/china/liquidity-injections-via-mlf', 'currency' => 3, 'unit' => 'M', 'cyclicity' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //通过反向回购注入流动性
            ['type' => 33, 'url' => 'https://zh.tradingeconomics.com/china/liquidity-injections-via-reverse-repo', 'currency' => 3, 'unit' => 'B', 'cyclicity' => 3, 'duration' => 1, 'btn' => '#dateSpansDiv > a:nth-child(3)'],
            //五期贷款利率
            ['type' => 34, 'url' => 'https://zh.tradingeconomics.com/china/loan-prime-rate-5y', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1],
            //银行贷款
            ['type' => 35, 'url' => 'https://zh.tradingeconomics.com/china/loans-to-banks', 'currency' => 3, 'unit' => 'M', 'cyclicity' => 1],
            //1 年期 MLF 利率
            ['type' => 36, 'url' => 'https://zh.tradingeconomics.com/china/1-year-mlf-rate', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1],
            //总计社会融资/私营部门贷款
            ['type' => 37, 'url' => 'https://zh.tradingeconomics.com/china/loans-to-private-sector', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1],
            //贷款增长/未偿贷款增长 (同比)
            ['type' => 38, 'url' => 'https://zh.tradingeconomics.com/china/loan-growth', 'currency' => 3, 'unit' => '%', 'cyclicity' => 1],
        ]);
    }

    public static function image(array $param, $currency): string
    {
//        print_r($param);exit();
        // 数据准备
        $xAxis = $param['x'];
        $yAxis = $param['y'];
        $manualScale[] = ['AxisID' => 0, 'Min' => $param['min'], 'Max' => $param['max']];
        $factors = [1, 1];
        $title = $param['title'];

        $color = [
            ["R" => 254, "G" => 117, "B" => 3],
            ["R" => 255, "G" => 189, "B" => 0],
            ["R" => 91, "G" => 175, "B" => 51],
            ["R" => 66, "G" => 157, "B" => 218]
        ];
        // 创建数据对象
        $data = new Data();

        foreach ($param['line'] as $k => $line) {
            $n = 'l' . $k;
            $data->addPoints($line, $n);
            $data->setPalette($n, $color[$k]);
        }

        $data->addPoints($xAxis, "X");
        $data->addPoints($yAxis, "");
        $data->setAbscissa("X");

        $data->setAxisName(0, "");  // y

        // 隐藏该系列
        $data->setSerieDrawable("", false);
        if (isset($param['setting']['yFormat']['unit'])) $data->setAxisUnit(0, 'K');

        // 创建图像
        $canvasWidth = $param['setting']['canvasWidth'];
        $canvasHeight = $param['setting']['canvasHeight'];
        $graphAreaWidth = $param['setting']['graphAreaWidth'];  // 图表区域宽度
        $graphAreaHeight = $param['setting']['graphAreaHeight']; // 图表区域高度
        $graphAreaX = ($canvasWidth - $graphAreaWidth) / 2;  // 计算X轴位置使内容居中
        $graphAreaY = 50;//($canvasHeight - $graphAreaHeight) / 2; // 计算Y轴位置使内容居中
        $image = new Image($canvasWidth, $canvasHeight, $data);
        // 设置字体
        $FontSize = 12;
        $FontName = '/Users/wangxiansheng/Workspace/fastapp-server/vendor/mpdf/mpdf/ttfonts/Sun-ExtA.ttf';
        $image->setFontProperties(['FontName' => $FontName, 'FontSize' => $FontSize, 'R' => 88, 'G' => 88, 'B' => 88,]);
        $str = explode('来源', $param['description']);
        $Text = '';
        $desc = [];
        foreach (mb_str_split($str[0]) as $k => $word) {
            $Text .= $word;
            $bbox = imagettfbbox($FontSize, 0, $FontName, $Text);
            $lineWidth = $bbox[2] - $bbox[0];
            if ($lineWidth > ($graphAreaWidth - (count($desc) ? 5 : 29))) {
                $desc[] = $Text;
                $Text = '';
            }
            if ($k == mb_strlen($str[0]) - 1) $desc[] = $Text;
        }
        if (isset($str[1])) $desc[] = '来源' . $str[1];
        foreach ($desc as $k => $txt) {
            $isend = str_contains($txt, '来源');
            $x = $k ? $graphAreaX : 98;
            $y = 310 + ($k * 20);
            $align = $isend ? TEXT_ALIGN_TOPMIDDLE : TEXT_ALIGN_TOPLEFT;
            if ($isend) {
                $x = 645;
                $FontSize = 10;
                $y += 5;
            }
            $image->drawText($x, $y, $txt, [
                'Align' => $align,
                'FontSize' => $FontSize,
                'R' => 89, 'G' => 89, 'B' => 89,
            ]);
        }

        // 设置标题
        $image->drawText(350, 20, $title, [
            'Align' => TEXT_ALIGN_TOPMIDDLE, 'R' => 77, 'G' => 77, 'B' => 79,
            'FontSize' => 16,
        ]);
        if (isset($param['setting']['title_tag'])) {
            $image->drawText($param['setting']['title_tag_x'], $param['setting']['title_tag_y'] ?? 22, $param['setting']['title_tag'], [
                'Align' => TEXT_ALIGN_TOPMIDDLE,
                'FontSize' => 10,
            ]);
        }
        if (isset($param['setting']['line_tag'])) {
            $len = mb_strlen($param['setting']['line_tag'][0]);
            foreach ($param['setting']['line_tag'] as $k => $v) {
                $n = mb_strlen($v) - $len;
                $x = $param['setting']['line_tag_x'];
                if ($n) $x += ($n * 7);
                $image->drawText($x, 22 + ($k * 22), '--' . $v, [
                    'Align' => TEXT_ALIGN_TOPMIDDLE, 'R' => $color[$k]['R'], 'G' => $color[$k]['G'], 'B' => $color[$k]['B'],
                    'FontSize' => 10,
                ]);
            }
        }
        // 设置绘图区域
        $image->setGraphArea($graphAreaX, $graphAreaY, $graphAreaX + $graphAreaWidth, $graphAreaY + $graphAreaHeight);

        // 绘制背景
        $image->drawFilledRectangle($graphAreaX, $graphAreaY, $graphAreaX + $graphAreaWidth, $graphAreaY + $graphAreaHeight, [
            'R' => 255, 'G' => 255, 'B' => 255, 'Dash' => false, // 禁用虚线背景
        ]);

        // 绘制坐标系（禁用网格线）
        $image->drawScale([
            'Factors' => $factors,//乘数因子
            'DrawArrows' => false,  // 箭头
            'Mode' => SCALE_MODE_MANUAL,
            'ManualScale' => $manualScale,
            'DrawSubTicks' => true, // 刻度线
            'SubTickR' => 0,
            'SubTickG' => 0,
            'SubTickB' => 0,
            'InnerSubTickWidth' => 2,
            'OuterSubTickWidth' => 4,
            'AxisAlpha' => 80,
            'AxisR' => 0,
            'AxisG' => 0,
            'AxisB' => 0,
            'TickAlpha' => 80,
            'TickR' => 0,
            'TickG' => 0,
            'TickB' => 0,
            'InnerTickWidth' => $param['setting']['InnerTickWidth'] ?? 2,
            'OuterTickWidth' => $param['setting']['OuterTickWidth'] ?? 4,
            'LabelSkip' => $param['setting']['LabelSkip'] ?? 0,
            'GridTicks' => 4,
            'GridR' => 255,
            'GridG' => 255,
            'GridB' => 255,
            'GridAlpha' => 100,
        ]);

        // 绘制趋势曲线（不绘制点）
        $image->drawLineChart([
            'DisplayValues' => false, // 不显示数据值
        ]);
        $path = BASE_PATH . '/p-chart/' . $currency . "/{$title}.jpg";
        $image->autoOutput($path);
        return $path;
    }

    public static function gen(): void
    {
        $mpdf = new \Mpdf\Mpdf([
            'mode' => 'utf-8',
            'format' => 'A4',
            'margin_top' => 30, // 设置顶部边距
            'margin_bottom' => 20, // 设置底部边距
            'margin_left' => 15,
            'margin_right' => 15,
            'default_font' => 'Sun-ExtA'
        ]);
        // 设置页眉和页脚
        $mpdf->SetHTMLHeader('<div style="text-align: center;border-bottom: 1px solid #FF7F00;padding-bottom: 3px">PDF 报告 - 页眉</div>');
        $mpdf->SetHTMLFooter('<div style="text-align: center;">页码：{PAGENO}/{nbpg}</div>');

        // 添加目录页
        $mpdf->AddPage();
        $mpdf->WriteHTML('<h1>目录</h1>');
        $stylesheet = "
    h1 {
        color: #FF7F00;
        font-size: 20px;
        margin-bottom: 10px;
    }
    ul {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    ul li {
        font-size: 14px;
        line-height: 1.8;
        color: #333;
    }
    ul ul {
        margin-left: 20px;
    }
    ul ul ul {
        margin-left: 20px;
    }
";
        $mpdf->WriteHTML("<style>$stylesheet</style>");

        $mpdf->Bookmark('内容目录：', 1, 10);
        $content = '
<h1>内容目录</h1>
<ul>
    <li>
    <div><b> 1. 美国 ..................................................................................4</b></div>
        <ul>
            <li>1.1 失业率 ............................................................................5</li>
            <li>1.2 通胀率 ............................................................................5</li>
            <li>1.3 M0 6</li>
            <li>1.4 M1,M2 7</li>
            <li>1.5 银行资产负债表 8</li>
            <li>1.6 美联储资产负债表 8</li>
            <li>1.7 外国债券投资 8</li>
            <li>1.8 联邦基金利率 8</li>
            <li>1.9 2,10年期国债收益率与有效联邦基金利率 8</li>
            <li>1.10 原油产量 8</li>
            <li>1.11 比特币汇率 8</li>
            <li>1.12 军费 8</li>
            <li>1.13 政府债务 8</li>
            <li>1.14 整体净资本流动 8</li>
            <li>1.16 贸易差额 8</li>
            <li>1.17 CPI 8</li>
            <li>1.18 消费者PMI 8</li>
        </ul>
    </li>
    <li><b>2. 日本 9</b>
        <ul>
            <li>2.1 失业率 9</li>
            <li>2.2 通胀率 9</li>
        </ul>
    </li>
    <li><b>3. 中国 1></b>
        <ul>
            <li>3.1 失业率 9</li>
            <li>3.2 通胀率 9</li>
        </ul>
    </li>
</ul>

';

//<h1>图表目录</h1>
//<ul>
//    <li>
//    图 1：恒生科技指数突破 2023 年初防疫政策优化后的高点.............................. 4
//    </li>
//</ul>
        $us = array_chunk([1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 20, 21, 22,], 2);
        $mpdf->WriteHTML($content);
        foreach ($us as $k => $item) {
            $mpdf->AddPage();
            if (!$k) {
                $mpdf->Bookmark('美国', 2, 10);
                $mpdf->WriteHTML('<h1 style="text-align: center;font-weight: bold;">美国</h1>');
            }
            $mpdf->Bookmark('美国：' . self::$title[1][$item[0]], 3, 10);
            foreach ($item as $v) {
                $imagePath = BASE_PATH . '/p-chart/1/' . self::$title[1][$v] . '.jpg';
                $mpdf->WriteHTML('<h1>美国：' . self::$title[1][$v] . '</h1>');
                $imageHtml = '<img src="' . $imagePath . '" width="700" height="300" style="margin-bottom: 10px;"/>';
                $mpdf->WriteHTML($imageHtml);
            }
        }


        $mpdf->Output(BASE_PATH . '/p-chart/report.pdf', 'F');
    }
}